import { App } from 'vue';
import { useUserStore } from '@/store/user';

/**
 * v-auth
 * 按钮权限指令
 */
const authDirective = {
  mounted(el: HTMLElement, binding: any) {
    const { value } = binding;
    const userStore = useUserStore();
    // 从 store 获取当前用户的按钮权限列表
    const permissions = userStore.permissions || [];

    if (value && value instanceof Array && value.length > 0) {
      // 如果指令的值是数组，则需要满足数组中所有权限
      const hasPermission = value.every(p => permissions.includes(p));
      if (!hasPermission) {
        // 如果没有权限，则直接从DOM中移除该元素
        el.parentNode?.removeChild(el);
      }
    } else if (typeof value === 'string') {
      // 如果指令的值是字符串，则检查是否包含该权限
      const hasPermission = permissions.includes(value);
      if (!hasPermission) {
        el.parentNode?.removeChild(el);
      }
    } else {
      throw new Error(`v-auth requires a string or an array of strings as value, but got ${value}`);
    }
  }
};

export function setupAuthDirective(app: App) {
  app.directive('auth', authDirective);
}
